<template>
  <div class="app-container">
    <h2 style="text-align: center;">发布新课程</h2>

    <!--步骤条-->
    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="提交审核"/>
    </el-steps>

    <!--基本信息表单-->
    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" style="width: 30%" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>

      <!-- 所属分类：级联下拉列表 -->
      <!-- 一级分类 -->
      <el-form-item label="课程类别">
        <!-- 一级分类 -->
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="请选择"
          @change="subjectLevelOneChanged">
          <el-option
            v-for="subject in subjectNestedList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>

        <!-- 二级分类 -->
        <el-select
          v-model="courseInfo.subjectId"
          placeholder="请选择">
          <el-option
            v-for="subject in subSubjectList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>
      </el-form-item>

      <!--课程讲师-->
      <el-form-item label="课程讲师">
        <el-select
          v-model="courseInfo.teacherId"
          placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
      </el-form-item>

      <!--课程简介 -->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description" style="width: 60%"/>
      </el-form-item>

      <!--课程封面 -->
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API + '/oss/file/upload?host=cover'"
          class="avatar-uploader">
          <img :src="courseInfo.cover" style="width: 500px">
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/>
      </el-form-item>

    </el-form>

    <el-form label-width="120px">
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next">保存并下一步</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>
<script>
import course from '@/api/edu/course'
import subject from '@/api/edu/subject'
import teacher from '@/api/edu/teacher'
import Tinymce from '@/components/Tinymce'

const defaultForm = {
  id: '',
  title: '',
  subjectId: '',
  subjectParentId: '',
  teacherId: '',
  lessonNum: 0,
  description: '',
  cover: process.env.OSS_PATH + '/cover/default.jpg',
  price: 0
}

export default {
  name: 'Info',
  components: { Tinymce },
  data() {
    return {
      courseInfo: defaultForm,
      saveBtnDisabled: false, // 保存按钮是否禁用
      subjectNestedList: [], // 一级分类列表
      subSubjectList: [], // 二级分类列表
      teacherList: [], // 讲师列表
      BASE_API: process.env.BASE_API
    }
  },
  // 监控路由变化，路由每发生一次变化，则执行一次init方法
  watch: {
    $router(to, form) {
      this.init()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      // 从路径判断id的值并获取该id课程信息
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        // 根据id获取课程信息
        this.fetchCourseInfoById(id)
      } else {
        // 使用对象扩展运算符，拷贝对象，而不是引用
        // 否则新增一条记录后，defaultForm就变成了之前新增的值，我们需要每次打开新增界面都是空白的，以及打开修改界面时是相关的信息
        this.courseInfo = { ...defaultForm }

        // 获取课程分类列表
        this.initSubjectList()

        // 获取讲师列表
        this.initTeacherList()
      }
    },

    fetchCourseInfoById(id) {
      course.getCourseInfoById(id).then(response => {
        this.courseInfo = response.data.item

        // 初始化获取分类列表
        subject.getNestedTreeList().then(responseSub => {
          this.subjectNestedList = responseSub.data.items
          for (let i = 0; i < this.subjectNestedList.length; i++) {
            if (this.subjectNestedList[i].id === this.courseInfo.subjectParentId) {
              this.subSubjectList = this.subjectNestedList[i].children
            }
          }
        })

        // 初始化获取讲师列表
        this.initTeacherList()
      })
    },

    initSubjectList() {
      subject.getNestedTreeList().then(response => {
        this.subjectNestedList = response.data.items
      })
    },

    initTeacherList() {
      teacher.getList().then(response => {
        this.teacherList = response.data.items
      })
    },

    // 当一级分类发生变化时的方法,同步更新二级分类的内容
    subjectLevelOneChanged(value) {
      // 遍历一级分类,找到对应的一级id,取出它的children
      for (let i = 0; i < this.subjectNestedList.length; i++) {
        if (this.subjectNestedList[i].id === value) {
          // 将children赋值给对应的list
          this.subSubjectList = this.subjectNestedList[i].children
          // 置空上一次选择的subjectId,避免一级分类切换后,二级分类依然不变的的情况
          this.courseInfo.subjectId = ''
        }
      }
    },

    next() {
      this.saveBtnDisabled = true
      // 判断courseInfo是否有id，如果没有，则是新数据，走新增
      if (!this.courseInfo.id) {
        this.saveData()
      } else {
        this.updateData()
      }
    },

    // 新增课程信息
    saveData() {
      course.saveCourseInfo(this.courseInfo).then(response => {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
        return response// 将响应结果传递给then
      }).then(response => {
        // 拿到后端返回的课程id，去对应的课程id界面进行修改
        this.$router.push({ path: '/edu/course/chapter/' + response.data.courseId })
      })
      // todo 这里不用catch,前端也会展示后端返回的错误信息,原因未知
      //   .catch((response) => {
      //   // debugger
      //   this.$message({
      //     type: 'error',
      //     message: '保存失败'
      //   })
      // })
    },

    // 修改课程信息
    updateData() {
      this.saveBtnDisabled = true
      course.updateCourseInfoById(this.courseInfo).then(response => {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
        return response
      }).then(response => {
        this.$router.push({ path: '/edu/course/chapter/' + this.courseInfo.id })
      })
    },

    // 封面上传成功后回调函数
    handleAvatarSuccess(res, file) {
      this.courseInfo.cover = res.data.url
    },

    // 封面上传之前的函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传封面图片只能是 JPG 格式')
      }
      if (!isLt2M) {
        this.$message.error('上传封面图片大小不能超过 2MB')
      }

      // 返回true则正常上传，返回false则停止上传
      return isJPG && isLt2M
    }

  }
}
</script>

<style scoped>
  .tinymce-container {
    line-height: 29px;
  }
</style>
